# 454.四数相加II
# 给你四个整数数组nums1、nums2、nums3和nums4 ，数组长度都是n ，请你计算有多少个元组(i, j, k, l)能满足：
# 0 <= i, j, k, l < n
# nums1[i] + nums2[j] + nums3[k] + nums4[l] == 0
#
# 示例1：
# 输入：nums1 = [1, 2], nums2 = [-2, -1], nums3 = [-1, 2], nums4 = [0, 2]
# 输出：2
# 解释：两个元组如下：
# 1.(0, 0, 0, 1) -> nums1[0] + nums2[0] + nums3[0] + nums4[1] = 1 + (-2) + (-1) + 2 = 0
# 2.(1, 1, 0, 0) -> nums1[1] + nums2[1] + nums3[0] + nums4[0] = 2 + (-1) + (-1) + 0 = 0
#
# 示例2：
# 输入：nums1 = [0], nums2 = [0], nums3 = [0], nums4 = [0]
# 输出：1

class Solution:
    def fourSumCount(self, nums1: int, nums2: int, nums3: int, nums4: int) -> int:
        dict_num1 = {}
        for i in range(len(nums1)):
            for j in range(len(nums2)):
                tmp = nums1[i] + nums2[j]
                if tmp not in dict_num1:
                    dict_num1[tmp] = [[i,j]]
                else:
                    dict_num1[tmp].append([i,j])
        dict_num2 = {}
        for i in range(len(nums3)):
            for j in range(len(nums4)):
                tmp = nums3[i] + nums4[j]
                if tmp not in dict_num2:
                    dict_num2[tmp] = [[i,j]]
                else:
                    dict_num2[tmp].append([i,j])
        res = 0
        for i in dict_num1:
            for j in dict_num2:
                if i + j == 0:
                    li = len(dict_num1[i])
                    lj = len(dict_num2[j])
                    tmp = li * lj
                    res += tmp
        return res

if __name__ == '__main__':
    nums1 = [1, 2]
    nums2 = [-2, -1]
    nums3 = [-1, 2]
    nums4 = [0, 2]
    tmp = Solution()
    res = tmp.fourSumCount(nums1,nums2,nums3,nums4)
    print(res)
    # 看了一下解法，因为只需要求计数，所以可以直接count计数，这样可以少循环一次。
